# coding=utf-8
from datetime import datetime, timedelta

import pandas as pd
from flask.blueprints import Blueprint
from flask import render_template, request, flash, redirect, url_for
from werkzeug.utils import secure_filename
import os
from src.api.response.R import R
from src.db.dbhelper import execute_sql
from src.db.flaskdb import db, del_model, update_and_not_commit, db_commit, add_models
from src.api.response.LayR import LayR
from src.db.flaskdb import add_model
from src.model.material_type import MaterialType
from src.model.material_type_quantity import MaterialTypeQuantity
from src.model.product_model_connect import ProductModelConnect
from src.util.pathutil import get_upload_dir
from pathlib import Path

material_api = Blueprint('material_api', __name__, url_prefix="/api/material")


@material_api.route('/material_manager_page', methods=["GET"])
def material_manager_page():
    return render_template("/material/zc_manager.html")


@material_api.route("/get_wl_list", methods=["POST"])
def get_wl_list():
    r = LayR()
    limit = request.form.get("limit")
    page = request.form.get("page")
    material_name = request.form.get("material_name")
    paginate = None
    if material_name is None or material_name == "":
        paginate = MaterialType.query
    else:
        paginate = MaterialType.query.filter(MaterialType.name.like(f"%{material_name}%"))
    pagination = paginate.paginate(page=int(page), per_page=int(limit))
    items = pagination.items
    total = pagination.total
    lis = []
    for item in items:
        lis.append(item.to_dict())
    r.data = lis
    r.count = total
    return r.to_dict()


@material_api.route("/material_init", methods=["POST"])
def material_init():
    r = R()
    # 获取所有的资产信息
    materials = MaterialType.query.filter(MaterialType.is_del == 0).all()
    material_quantities = []
    ds = datetime.now()
    end = ds + timedelta(days=7)
    for material in materials:
        material_quantity = MaterialTypeQuantity()
        material_quantity.material_id = material.id
        material_quantity.material_name = material.name
        material_quantity.material_quantity = 0
        material_quantity.effect_start = ds
        material_quantity.effect_end = end
        material_quantity.m_type = material.m_type
        material_quantity.create_time = ds
        material_quantities.append(material_quantity)
    if len(material_quantities) > 0:
        sql = "delete from material_type_quantity where is_del = 0 "
        execute_sql(sql)
        add_models(material_quantities)
    r.msg = "初始化成功"
    r.code = 200
    return r.to_dict()


@material_api.route("/add_zc", methods=["POST"])
def add_zc():
    material_name = request.form.get("material_name")
    t_type = request.form.get("t_type")
    if material_name is None or material_name == "":
        return {
            "code": 500,
            "msg": "资产名称为空"
        }
    first = MaterialType.query.filter(MaterialType.name == material_name).filter(MaterialType.m_type == t_type).filter(
        MaterialType.is_del == 0).first()
    if first is None:
        ds = datetime.now()
        # 新增
        material = MaterialType()
        material.name = material_name
        material.is_del = 0
        material.create_time = ds
        material.m_type = t_type
        add_model(material)
        # material_quantity = MaterialTypeQuantity()
        # material_quantity.material_id = material.id
        # material_quantity.material_name = material_name
        # material_quantity.material_quantity = 0
        # material_quantity.create_time = ds
        # add_model(material_quantity)
        return {
            "code": 200,
            "msg": "新增成功"
        }
    else:
        return {
            "code": 500,
            "msg": "资产名称已经存在"
        }


@material_api.route("/del", methods=["POST"])
def del_zc():
    material_id = request.form.get("id")
    first = MaterialType.query.filter(MaterialType.id == material_id).first()
    if first is not None:
        del_model(first)
        material_id = first.id
        quantity_mo = MaterialTypeQuantity.query.filter(MaterialTypeQuantity.material_id == material_id).first()
        del_model(quantity_mo)
    return {
        "code": 200,
        "msg": "删除成功"
    }


@material_api.route('/quantity_manager_page', methods=["GET"])
def quantity_manager_page():
    return render_template("/material/quantity_manager.html")


@material_api.route("/get_quantity_list", methods=["POST"])
def get_quantity_list():
    r = LayR()
    limit = request.form.get("limit")
    page = request.form.get("page")
    material_name = request.form.get("material_name")
    paginate = None
    if material_name is None or material_name == "":
        paginate = MaterialTypeQuantity.query
    else:
        paginate = MaterialTypeQuantity.query.filter(MaterialTypeQuantity.material_name.like(f"%{material_name}%"))
    pagination = paginate.paginate(page=int(page), per_page=int(limit))
    items = pagination.items
    total = pagination.total
    lis = []
    for item in items:
        lis.append(item.to_dict())
    r.data = lis
    r.count = total
    return r.to_dict()


@material_api.route("/update_quantity", methods=["POST"])
def update_quantity():
    material_id = request.form.get("material_id")
    material_quantity = request.form.get("material_quantity")
    first = MaterialTypeQuantity.query.filter(MaterialTypeQuantity.material_id == material_id).first()
    if first is None:
        return {
            "code": 500,
            "msg": "修改失败"
        }
    first.material_quantity = material_quantity
    db_commit()
    return {
        "code": 200,
        "msg": "修改成功"
    }


@material_api.route("/get_material", methods=["POST"])
def get_material():
    materials = MaterialType.query.filter(MaterialType.is_del == 0).all()
    tree_materials = []
    for i in materials:
        tree_materials.append({
            "id": i.id,
            "title": f'{i.m_type}_{i.name}',
            "field": i.name,
            "checked": False,
            "spread": True,
            "children": []
        })
    return tree_materials


@material_api.route("/get_all_material", methods=["POST"])
def get_all_material():
    materials = MaterialType.query.all()
    material_list = []
    for i in materials:
        item = i.to_dict()
        m_type = item.get("m_type")
        name = item.get("name")
        name = f'{m_type}_{name}'
        item["name"] = name
        material_list.append(item)
    r = R()
    r.code = 200
    r.data = material_list
    return r.to_dict()


@material_api.route("/get_all_connection", methods=["POST"])
def get_all_connections():
    product_id = request.form.get("product_id")
    all_connections = ProductModelConnect.query.filter(ProductModelConnect.pro_id == product_id).filter(
        ProductModelConnect.is_del == 0).all()
    all_connection_list = []
    for i in all_connections:
        all_connection_list.append(i.to_dict())
    r = R()
    r.code = 200
    r.data = all_connection_list
    return r.to_dict()


@material_api.route("/upload_material", methods=["POST"])
def upload_material():
    """上传文件"""
    r = R()
    if 'file' not in request.files:
        flash('No file part')
        return r.setResponse(code=500, msg="请先选择文件").to_dict()

    file = request.files['file']
    if file.filename == '':
        flash('No selected file')
        return r.setResponse(code=500, msg="请先选择文件").to_dict()

    if file:  # 这里可以加入文件类型判断等逻辑
        filename = secure_filename(file.filename)
        if filename.endswith("xlsx") or filename.endswith("xls"):
            file_path = Path.joinpath(get_upload_dir(), filename)
            file.save(file_path)
            # 读取文件
            df = pd.read_excel(file_path)
            print(df)
            file_path.unlink()
        else:
            return r.setResponse(code=500, msg="只允许上传以xlsx和xls结尾的Excel文件").to_dict()
        return r.setResponse(code=200, msg="上传成功").to_dict()
